<?php
namespace Api\Controller;

use Common\Model\AccountModel;
use Common\Model\GoldModel;
use Common\Model\User\UserViewLogModel;
use Common\Model\User\UserVipLogModel;
use Common\Model\UserCardListModel;
use Common\Model\UserModel;
use Common\Model\Vip\VipCodeModel;
use Common\Util\AgentData;
use Common\Util\BaseData;
use Common\Util\GoodsData;
use Common\Util\SelfUserData;
use Common\Util\ShopData;
use Common\Util\SPWxPay;
use Common\Util\UserData;
use Common\Util\WechatUtil;
use Common\WxPay\WxPayUnifiedOrder;
use Services\Article\ArticleService;
use Services\Fenxiao\FenxiaoService;
use Services\Upload\OssFileService;
use Services\User\UserService;
use Services\User\UserViewLogService;
use Services\Vip\Enums\AwardVipDayNumberSceneEnum;
use Services\WxGongZhong\WxGongZhongService;

class UserController extends AuthController
{

    public function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        $user_info = $this->checkUserUtoken();
        $data['user_info'] = $user_info;
        $app_setting = BaseData::getAppSetting();
        $jssdk_url = $app_setting['app_domain'] . '/h5/pages/my/my';
        $data['jssdk_param_data'] = $this->getJssdkData($jssdk_url);
        $data['weixin_kefu'] = $app_setting['weixin_kefu'];
        $this->return_app_data(1, $data);
    }

    public function collectList()
    {
        $user_info = $this->checkUserUtoken();
        $user_id = $user_info['id'];
        //		$page_size = $_GET['page_size'] ? $_GET['page_size'] : 1;
        //		$page_limit = $_GET['page_limit'] ? $_GET['page_limit'] : 10;
        $collect_info = [];
        $type = $_GET['type'] ? intval($_GET['type']) : 0;
        if ($type == 1) {
            //	商品信息
            $collect_list = M("user_collect_goods")->where("user_id={$user_id}")->order("add_time")->select();
            foreach ($collect_list as $key => $val) {
                if ($goods_info = M("shop_goods_list")->where("id={$val['goods_id']}")->find()) {
                    $collect_info[$key]['id'] = $val['goods_id'];
                    $collect_info[$key]['logo'] = $goods_info['goods_pic'];
                    $collect_info[$key]['is_qixian'] = $goods_info['is_qixian'];
                    $collect_info[$key]['active'] = false;
                    $collect_info[$key]['goods_jianjie'] = $goods_info['goods_jianjie'];
                    $collect_info[$key]['q_qixian_etime'] = $goods_info['q_qixian_etime'];
                    $collect_info[$key]['goods_name'] = $goods_info['goods_name'];
                    $collect_info[$key]['sale_all_num'] = $goods_info['sale_all_num'];
                    $collect_info[$key]['false_sale_all_num'] = $goods_info['false_sale_all_num'];
                    $collect_info[$key]['goods_number'] = $goods_info['goods_number'];
                    $collect_info[$key]['goods_price'] = $goods_info['goods_price'];
                    $collect_info[$key]['remark_price'] = $goods_info['market_price'];
                }
            }
        } else {
            //	店铺信息
            $collect_list = M("user_collect_shop")->where("user_id={$user_id}")->order("add_time")->select();
            foreach ($collect_list as $k => $v) {
                if ($shop_info = M("shop_list")->where("id={$v['shop_id']}")->find()) {
                    $collect_info[$k]['id'] = $shop_info['id'];
                    $collect_info[$k]['shop_name'] = $shop_info['shop_name'];
                    $collect_info[$k]['yingye_btime'] = $shop_info['yingye_btime'] ? date("H:i", $shop_info['yingye_btime']) : '';
                    $collect_info[$k]['yingye_etime'] = $shop_info['yingye_etime'] ? date("H:i", $shop_info['yingye_etime']) : '';
                    $collect_info[$k]['logo'] = $shop_info['shop_logo'];
                }
            }
        }
        $data['collect_list'] = $collect_info;
        $this->return_app_data(1, $data);
    }

    // 只做自己的名片信息
    public function addCard()
    {
        $user_info = $this->checkUserUtoken();
        $card_form = $_POST['card_form'] ? json_decode($_POST['card_form'], true) : [];
        if (empty($card_form['avatar'])) {
            $this->return_app_data(0, '请上传头像');
        }
        if (empty($card_form['name'])) {
            $this->return_app_data(0, '请输入姓名');
        }
        //		if(empty($card_form['address'])){
        //			$this->return_app_data(0, '请输入地址信息');
        //		}
        //		if(empty($card_form['latitude'])){
        //			$this->return_app_data(0, '请选择位置坐标');
        //		}
        //		if(empty($card_form['introduce'])){
        //			$this->return_app_data(0, '请输入简介');
        //		}
        //		if(empty($card_form['labels'][0])){
        //			$this->return_app_data(0, '请选择标签');
        //		}
        if ($card_form['weixinQrcode']) {
            $weixinQrcode = extract_path_from_url($card_form['weixinQrcode']);
        } else {
            $weixinQrcode = '';
        }
        //		判断是否已经制作了名片
        $card_find = M("user_card_list")->where(['user_id' => $user_info['id']])->find();
        $addData = [
            'user_id' => $user_info['id'],
            'c_touxiang' => $card_form['avatar'],
            'c_cn_true_name' => $card_form['name'],
            'c_phone' => $card_form['phone'],
            'c_weixin' => $card_form['weixin'],
            'c_weixin_img' => $weixinQrcode,
            'c_email' => $card_form['email'],
            'c_address' => $card_form['address'],
            'c_lat' => $card_form['latitude'],
            'c_lng' => $card_form['longitude'],
            'jianjie' => $card_form['introduce'],
            'zhiye_label' => implode(",", $card_form['labels']),
            'updated_at' => get_now_date()
        ];
        $user_m = new UserModel();
        if ($card_find) {
            $addAction = M("user_card_list")->where(['id' => $card_find['id']])->save($addData);
            if ($addAction) {
                M("user")->where(['id' => $user_info['id']])->save([
                    'user_headimg' => $card_form['avatar'],
                    'user_nickname' => $card_form['name'],
                    'user_true_phone' => $card_form['c_phone'],
                    'update_time' => time(),
                ]);
                $this->return_app_data(1, '更新成功');
            } else {
                $this->return_app_data(0, '添加失败');
            }
        } else {
            $addData['created_at'] = get_now_date();
            $addAction = M("user_card_list")->add($addData);
            if ($addAction) {
                M("user")->where(['id' => $user_info['id']])->save([
                    'user_headimg' => $card_form['avatar'],
                    'user_nickname' => $card_form['name'],
                    'updated_at' => get_now_date()
                ]);
                //赠送用户三天的VIP
                (new UserService())->openVip($user_info['id'], AwardVipDayNumberSceneEnum::SCENE_REGISTER, UserVipLogModel::CHANNEL_REGISTER);
                //添加一个默认分类
                $addData = [
                    'user_id' => $user_info['id'],
                    'cate_name' => '默认分类',
                    'cate_status' => 1,
                    'add_time' => time(),
                    'update_time' => time(),
                ];
                M("user_cms_category")->add($addData);
                $this->return_app_data(1, '添加成功');
            } else {
                $this->return_app_data(0, '添加失败');
            }
        }

        //		if(empty($card_form['phone'])){
        //			$this->return_app_data(0, '请上传手机号');
        //		}
        //		if(isMobile($card_form['phone'])){
        //			$this->return_app_data(0, '请上传正确的手机号');
        //		}
    }

    //	获取收藏列表
    public function myCollect()
    {
        $user_info = $this->checkUserUtoken();
        $page_size = $_POST['page_size'] ? intval($_POST['page_size']) : 0;
        $page_limit = $_POST['page_limit'] ? intval($_POST['page_limit']) : 0;
        $u_lat = $_POST['lat'] ? trim($_POST['lat']) : 0;
        $u_lng = $_POST['lng'] ? trim($_POST['lng']) : 0;
        if (!empty($u_lat) && !empty($u_lng)) {
            $sql_filed = "c.*,cc.id as collect_id,(2 * 6378.137* ASIN(SQRT(POW(SIN(3.1415926535898*(" . $u_lat . "-c_lat)/360),2)+COS(3.1415926535898*" . $u_lat . "/180)* COS(c_lat * 3.1415926535898/180)*POW(SIN(3.1415926535898*(" . $u_lng . "-c_lng)/360),2))))*1000 as juli_number";
        } else {
            $sql_filed = "c.*,cc.id as collect_id,0 as juli_number";
        }
        $startnum = ($page_size - 1) * $page_limit;
        $data_list = M("user_card_list_collect")
            ->alias('cc')
            ->join('left join ' . C('DB_PREFIX') . 'user_card_list' . ' c on c.id = cc.card_id')
            ->where(['cc.user_id' => $user_info['id']])
            ->field($sql_filed)
            ->order("c.id desc")
            ->limit($startnum, $page_limit)
            ->select();
        foreach ($data_list as $key => $val) {
            if ($val['juli_number'] == 0 || empty($val['juli_number'])) {
                $data_list[$key]['info_juli_num'] = 0;
                $data_list[$key]['info_juli_mi'] = '0m';
            } else {
                if ($val['juli_number'] >= 1000) {
                    $leng_km = sprintf("%.1f", $val['juli_number'] / 1000);
                    $data_list[$key]['info_juli_mi'] = $leng_km . 'km';
                } else {
                    $data_list[$key]['info_juli_mi'] = sprintf("%.1f", $val['juli_number']) . 'm';
                }
                $data_list[$key]['info_juli_num'] = round($val['juli_number']);
            }
            $data_list[$key]['zhiye_label'] = $val['zhiye_label'] ? explode(',', $val['zhiye_label']) : [];
        }
        $this->return_app_data(1, $data_list);
    }

    //    取消收藏
    public function collectCancel()
    {
        //			商品
        $collect_id = $_POST['collect_id'] ? intval($_POST['collect_id']) : 0;
        $map['id'] = $collect_id;
        $cancel = M("user_card_list_collect")->where($map)->delete();
        if ($cancel) {
            $this->return_app_data(1, "取消成功");
        } else {
            $this->return_app_data(0, "取消失败");
        }
    }

    //	获取好友列表
    public function myFriend()
    {
        $user_info = $this->checkUserUtoken();
        $page_size = $_POST['page_size'] ? intval($_POST['page_size']) : 0;
        $page_limit = $_POST['page_limit'] ? intval($_POST['page_limit']) : 0;
        $tabCurrent = $_POST['tabCurrent'] ? intval($_POST['tabCurrent']) : 0;
        $user_m = new UserModel();
        if ($tabCurrent == 0) {
            //			有效好友
            $map['invite_is_true'] = 1;
        } else {
            $map['invite_is_true'] = 0;
        }
        $map['referrer_user_id'] = $user_info['id'];
        $startnum = ($page_size - 1) * $page_limit;
        $friend_list = $user_m
            ->where($map)
            ->order("id desc")
            ->limit($startnum, $page_limit)
            ->select();
        $card_m = new UserCardListModel();
        foreach ($friend_list as $key => $val) {
            $card_info = $card_m->where(['user_id' => $val['id']])->find();
            if ($card_info) {
                $friend_list[$key]['is_make_card'] = 1;
                $friend_list[$key]['jianjie'] = $card_info['jianjie'];
                $friend_list[$key]['zhiye_label'] = $card_info['zhiye_label'] ? explode(",", $card_info['zhiye_label']) : [];
            } else {
                $friend_list[$key]['jianjie'] = '';
                $friend_list[$key]['is_make_card'] = 0;
                $friend_list[$key]['zhiye_label'] = [];
            }
            $friend_list[$key]['invite_date'] = date("Y-m-d H:i:s", $val['add_time']);
        }
        $this->return_app_data(1, $friend_list);
    }

    //	获取名片信息
    public function getCardData()
    {
        $user_info = $this->checkUserUtoken();
        //		判断是否已经制作了名片
        $card = new UserCardListModel();
        $card_find = $card->getInfo(['user_id' => $user_info['id']]);
        if ($card_find) {
            $card_find['is_make_card'] = 1;
            $card_find['zhiye_label'] = $card_find['zhiye_label'] ? explode(',', $card_find['zhiye_label']) : [];
            $card_find['c_weixin_img'] = OssFileService::getOssUrl($card_find['c_weixin_img']);
        } else {
            $card_find['is_make_card'] = 0;
            $card_find['user_nickname'] = $user_info['user_nickname'];
            $card_find['c_touxiang'] = $user_info['user_headimg'];
        }
        $this->return_app_data(1, $card_find ? $card_find : false);
    }

    public function vipPay()
    {
        $user_info = $this->checkUserUtoken();
        $pay_type = $_POST['tabCurrent'] ? intval($_POST['tabCurrent']) : 0;
        $day_type = $_POST['costCurrent'] ? intval($_POST['costCurrent']) : 0;
        $check_code = $_POST['check_code'] ? trim($_POST['check_code']) : '';
        $vip_type = 1;
        $user_m = new UserModel();
        if ($pay_type == 0) {
            $this->return_app_data(0, '暂不支持该方式');
            //			微信支付
            if ($day_type == 0) {
                //				一月
                $amount = 98;
            } elseif ($day_type == 1) {
                //				十二月
                $amount = 298;
            } elseif ($day_type == 2) {
                $vip_type = 2;
                //				终身
                $amount = 598;
            }
            $pay_order = 'V' . date("YmdHis") . $user_info['id'] . mt_rand(1111, 9999);
            $notify_url = $this->this_app_config['app_domain'] . "/index.php/Return/payVipResult";
            $vipData = [
                'user_id' => $user_info['id'],
                'vip_type' => $vip_type,
                'pay_money' => $amount,
                'add_time' => time(),
                'update_time' => time(),
            ];
            $addVip = M("user_vip_pay")->add($vipData);
            if ($addVip) {
                $parameters_data = [
                    'body' => '购买商品',
                    'totalFee' => $amount,
                    'out_trade_no' => $pay_order,
                    'notify_url' => $notify_url,
                ];
                $return_data = WechatUtil::unifiedOrder($user_info['user_openid'], $parameters_data);
                $this->return_app_data(1, $return_data);
            } else {
                $this->return_app_data(0, '支付失败');
            }
        } else {
            //			激活码激活方式
            if (empty($check_code)) {
                $this->return_app_data(0, '请输入激活验证码');
            }
            $map['code'] = $check_code;
            $map['is_use'] = VipCodeModel::NOT_USE;
            $vipCodeModel = new VipCodeModel();
            $findSetting = $vipCodeModel->where($map)->order("id asc")->find();
            if (!$findSetting) {
                $this->return_app_data(0, '请填写正确的验证码');
            }
            $user_m->startTrans();

            //赠送用户VIP
            $sendAction = (new UserService())->openVip($user_info['id'], $findSetting['vip_day'], UserVipLogModel::CHANNEL_CODE);
            if ($sendAction) {
                $save_status = $vipCodeModel->where(['id' => $findSetting['id']])->save([
                    'is_use' => 1,
                    'use_user_id' => $user_info['id'],
                    'update_time' => time(),
                ]);
                //todo:累计用户的累计有效拉新人数&发放奖励
                (new FenxiaoService())->firstRewardGrant($user_info['id']);
                $user_m->commit();
                $this->return_app_data(1, 'VIP权益生效');
            } else {
                $user_m->rollback();
                $this->return_app_data(0, '激活失败');
            }
        }
    }

    //	分享图片
    public function shareImg()
    {
        $user_info = $this->checkUserUtoken();
        //		邀请码
        $haibai_url = '';
        if (!empty($user_info['tg_haibai_url'])) {
            $haibai_url = $user_info['tg_haibai_url'];
        } else {
            if ($shop_pay_rcode_url = $this->makeUserHaibao()) {
                $haibai_url = $shop_pay_rcode_url;
            }
        }
        $data['tg_haibai_erweim_url'] = $haibai_url;
        $data['tg_haibai_bg'] = $this->this_app_config['shop_fenxiao_bg_img'];
        $this->return_app_data(1, $data);
    }

    public function makeUserHaibao()
    {
        $user_info = $this->checkUserUtoken();
        $t_user = M("user");
        $user_id = $user_info['id'];
        Vendor('phpqrcode.phpqrcode');
        $shop_pay_url = $this->this_app_config['app_domain'] . "/h5/pages/Index/index?tg_user_id=" . $user_id;
        $shop_nologo_img_path = SITE_PATH . 'Data/shoprcode/user_nologo_rcode_' . $user_id . ".png";
        \QRcode::png($shop_pay_url, $shop_nologo_img_path, QR_ECLEVEL_H, 4, 2, false, 0xFFFFFF, 0x000000);
        if (file_exists($shop_nologo_img_path) == false) {
            return false;
        }
        $beijing = imagecreatefromstring(file_get_contents($this->this_app_config['shop_fenxiao_bg_img_upload']));
        //		$image_3 = imageCreatetruecolor(720,1280);
        //		$color = imagecolorallocate($image_3, 255, 255, 255);
        //		imagefill($image_3, 0, 0, $color);
        //		imagecopyresampled($image_3,$beijing,0,0,0,0,imagesx($beijing),imagesy($beijing),imagesx($beijing),imagesy($beijing));
        //		imagecopymerge($image_3,imagecreatefrompng($shop_nologo_img_path), 250,1050,0,0,212,212,100);//左，上，右，下，宽度，高度，透明度

        //		$shop_pay_rcode_path = SITE_PATH."Data/shoprcode/user_haibao_rcode_".$this->this_user_id. '.png';
        //		imagepng($image_3,$shop_pay_rcode_path);
        //		imagedestroy($image_3);
        if ($shop_pay_rcode_url = BaseData::uploadStaticFile("user_haibao_rcode_" . $user_id . time(), $shop_nologo_img_path,
            $is_source = false)) {
            $s_s_data['tg_haibai_url'] = $shop_pay_rcode_url;
            $s_s_data['update_time'] = time();
            if ($t_user->where("id={$user_id}")->save($s_s_data)) {
                return $shop_pay_rcode_url;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    //申请代理
    public function join()
    {
        $user_info = $this->checkUserUtoken();
        $user_id = $user_info['id'];
        $t_agent_apply = M("agent_apply");
        $user_name = $_POST['user_name'] ? $_POST['user_name'] : '';
        $user_name = $this->formatFormText($user_name);
        if (empty($user_name)) {
            $this->return_app_data(0, '请输入您的姓名');
        }
        $user_phone = $_POST['user_phone'] ? $_POST['user_phone'] : '';
        $user_address = $_POST['user_address'] ? $_POST['user_address'] : '';
        if (isMobile($user_phone) == false) {
            $this->return_app_data(0, '请输入您的手机号码');
        }
        if (empty($user_address)) {
            $this->return_app_data(0, '请选择地区');
        }
        //		判断是否提交
        $find = $t_agent_apply->where(['user_id' => $user_id, 'user_address' => $user_address])->find();
        if ($find) {
            $this->return_app_data(0, '您已经提交过该区域的代理申请');
        }
        $s_u_data['user_id'] = $user_id;
        $s_u_data['user_name'] = $user_name;
        $s_u_data['user_phone'] = $user_phone;
        $s_u_data['user_address'] = $user_address;
        $s_u_data['add_time'] = time();
        $s_u_data['update_time'] = time();
        if ($t_agent_apply->add($s_u_data)) {
            $this->return_app_data(1, '提交成功，请等待客服与您联系');
        } else {
            $this->return_app_data(0, '提交失败，请重试');
        }
    }

    public function deleteAddress()
    {
        $address_id = $_GET['address_id'] ? trim($_GET['address_id']) : 0;
        if (M("user_address")->where("id={$address_id}")->delete()) {
            $this->return_app_data(1, '删除成功');
        } else {
            $this->return_app_data(0, '删除失败');
        }
    }

    public function feedBack()
    {
        $user_info = $this->checkUserUtoken();
        $user_id = $user_info['id'];
        $content = $_POST['content'] ? trim($_POST['content']) : '';
        $images = $_POST['images'] ? json_decode($_POST['images'], true) : [];
        $images_arr = [];
        $images_info = '';
        if ($images) {
            foreach ($images as $key => $val) {
                $images_arr[$key] = $val['url'];
            }
            $images_info = implode(',', $images_arr);
        }
        if (empty($content)) {
            $this->return_app_data(0, '请填写反馈意见');
        }
        $fankui['user_id'] = $user_id;
        $fankui['content'] = $content;
        $fankui['images'] = $images_info;
        $fankui['add_time'] = time();
        $fankui['update_time'] = time();
        $fankuiAdd = M("user_feedback")->add($fankui);
        if ($fankuiAdd) {
            $this->return_app_data(1, '提交成功');
        } else {
            $this->return_app_data(0, '提交失败');
        }
    }

    public function getXieyi()
    {
        $title = $_POST['title'] ? trim($_POST['title']) : '';
        $app_setting = BaseData::getAppSetting(true);
        $content = $app_setting[$title];
        $this->return_app_data(1, $content);
    }

    public function messageCate()
    {
        $user_info = $this->checkUserUtoken();
        $user_id = $user_info['id'];
        //		消息
        $shop['user_id'] = $user_id;
        $shop['status'] = 0;
        $shop['message_type'] = 1;
        $shop_count = M("message")->where($shop)->count();
        $goods['user_id'] = $user_id;
        $goods['status'] = 0;
        $goods['message_type'] = 2;
        $goods_count = M("message")->where($goods)->count();
        $data['shop_count'] = $shop_count;
        $data['goods_count'] = $goods_count;
        $this->return_app_data(1, $data);
    }

    public function messageList()
    {
        $user_info = $this->checkUserUtoken();
        $type = $_GET['type'] ? intval($_GET['type']) : 1;
        $map['message_type'] = $type;
        $map['user_id'] = $user_info['id'];
        $message_list = M("message")->where($map)->select();
        M("message")->where($map)->save(['status' => 1, 'update_time' => time()]);
        $this->return_app_data(1, $message_list);
    }

    public function accountLog()
    {
        $user_info = $this->checkUserUtoken();
        $page_size = $_GET['page_size'] ? $_GET['page_size'] : 1;
        $page_limit = $_GET['page_limit'] ? $_GET['page_limit'] : 10;
        $user_id = $user_info['id'];
        $accountData['user_id'] = $user_id;
        $accountData['user_type'] = 4;
        $account_list = M("all_account_user_log")->where($accountData)->order("add_time asc")->page($page_size, $page_limit)->select();
        foreach ($account_list as $key => $val) {
            $account_list[$key]['add_time'] = date("Y-m-d H:i", $val['add_time']);
        }
        $this->return_app_data(1, $account_list);
    }

    //	用户浏览轨迹
    public function track()
    {
        $user_info = $this->checkUserUtoken();
        //		获取用户浏览轨迹
        $keyword_search = $_POST['keyword_search'] ? trim($_POST['keyword_search']) : '';
        if ($keyword_search) {
            $where['user_nickname'] = ['like', '%' . $keyword_search . '%'];
        }
        $where['view_user_id'] = ['eq', $user_info['id']];
//		$track_list = M("user_view_log")
//			->alias('v')
//			->join('left join '.C('DB_PREFIX').'user'.' u on u.id = v.user_id')
//			->where($where)
//			->group("v.user_id")
//			->field("v.*,u.user_nickname,u.user_headimg")
//			->order('v.id desc')
//			->select(false);
        $track_list = M()->query(sprintf("select * from (
	SELECT
	v.*,
	u.user_nickname,
	u.user_headimg,
	uc.id as card_id
FROM
	user_view_log v
	LEFT JOIN user u ON u.id = v.user_id 
	LEFT JOIN user_card_list uc ON uc.id = v.user_id 
WHERE
	`view_user_id` = %s
order by created_at desc
) as r1 
group by user_id 
order by id desc", $user_info['id']));

        $card_m = new UserCardListModel();
        $userService = new UserService();
        foreach ($track_list as $key => $val) {
            $all_view_count = M("user_view_log")->where([
                'view_user_id' => $user_info['id'], 'user_id' => $val['user_id'],
            ])->count();
            $show_view_find = M("user_view_log")->where([
                'view_user_id' => $user_info['id'], 'user_id' => $val['user_id'],
            ])->order("id desc")->find();
            //			判断浏览用户是否创建了名片
            $card_info = $card_m->getInfo(['user_id' => $val['user_id']]);

            $weixin = '';
            if ($card_info) {
                $weixin = $card_info['c_weixin'];
            }
            //意向客户判定
            $track_list[$key]['is_potential_customer'] = $userService->judgeUserIsPotentialCustomer($val['user_id'], $user_info['id']);
            //判定用户是否存在高意向
            $track_list[$key]['view_user_card_info_id'] = $card_info ? $card_info['id'] : 0;
            $track_list[$key]['weixin'] = $weixin ? $weixin : '';
            $track_list[$key]['all_view_count'] = $all_view_count;
            $track_list[$key]['zuijin_view_time'] = format_date(strtotime($show_view_find['created_at']));;
        }
        //总访客
        $viewAllUser = (new UserViewLogService())->setParams([
            'view_user_id' => $this->getUserId(),
        ])->getViewAllUser();
        $today_view_number = M("user_view_log")
            ->where(['view_user_id' => $user_info['id'], 'view_day' => date("Y-m-d")])
            ->group("user_id")
            ->select();
        $data['view_log_tip_type'] = $user_info['view_log_tip_type'];
        $data['is_vip'] = $user_info['is_vip'];
        $data['track_list'] = $track_list;
        $data['all_view_number'] = $viewAllUser ? count($viewAllUser) : 0;
        $data['today_view_number'] = $today_view_number ? count($today_view_number) : 0;
        //		获取设置
        $this->return_app_data(1, $data);
    }

    //	获取用户的浏览轨迹
    public function getUserViewLog()
    {
        $user_info = $this->checkUserUtoken();
        $show_user_id = $_POST['show_user_id'] ? intval($_POST['show_user_id']) : 0;
        $all_view_number = M("user_view_log")->where([
            'view_user_id' => $user_info['id'],
            'user_id' => $show_user_id,
        ])->group("view_day")->field("view_day,created_at")->order("id desc")->select();
        $userService = new UserService();
        foreach ($all_view_number as $key => $val) {
            $view_list = M("user_view_log")->where([
                'view_user_id' => $user_info['id'],
                'user_id' => $show_user_id,
                'view_day' => $val['view_day'],
            ])->order("id desc")->select();
            $time = count($view_list);
            foreach ($view_list as $key1 => $val1) {
                if ($val1['view_type'] == 1) {
                    $title = '个人主页';
                    $cardInfo = $userService->card($val1['user_id']);
                    $view_list[$key1]['extend'] = $cardInfo ? [
                        'id' => arr_get($cardInfo, 'id'),
                        'image' => arr_get($cardInfo, 'lit_pic'),
                        'title' => '我的名片',
                    ] : [];
                } else {
                    $articleInfo = (new ArticleService())->articleInfo($val1['model_id'], ['id', 'title', 'lit_pic']);
                    $view_list[$key1]['extend'] = [
                        'id' => arr_get($articleInfo, 'id'),
                        'image' => arr_get($articleInfo, 'lit_pic'),
                        'title' => arr_get($articleInfo, 'title'),
                    ];
                    $title = "文章《" . arr_get($articleInfo, 'title') . "》";
                }
                $view_list[$key1]['view_count'] = $time;
                $view_list[$key1]['view_title'] = $title;
                $view_list[$key1]['view_add_time'] = $val1['created_at'];
                $view_list[$key1]['view_second_des'] = ($val1['view_second'] > 60) ? floor($val1['view_second'] / 60) . '分钟' : max($val1['view_second'], 1) . '秒';
                $view_list[$key1]['all_view_second_des'] = ($val1['view_all_time'] > 60) ? floor($val1['view_all_time'] / 60) . '分钟' : max($val1['view_all_time'], 1) . '秒';
                $time--;
            }
            $all_view_number[$key]['zuijin_view_time'] = format_date(strtotime($val['created_at']));;
            $all_view_number[$key]['view_list'] = $view_list ? $view_list : [];
        }
        $info = UserData::getUserInfoById($show_user_id);
        $data['user_headimg'] = $info['user_headimg'];
        $data['user_nickname'] = $info['user_nickname'];
        $data['c_weixin'] = $info['c_weixin'];
        $data['list'] = $all_view_number;
        $this->return_app_data(1, $data);
    }

    /**
     * 新版的访问记录
     * @return void
     */
    public function getUserViewLogV2()
    {
        $user_info = $this->checkUserUtoken();
        $targetUserId = arr_get($_GET, 'target_user_id',0);
        $sql = sprintf("SELECT
id,type,view_user_id,user_id,model_id,view_second,
count(id) as count,
sum(view_second) as all_view_second,
max(created_at) as last_created_at
FROM
	user_view_log 
WHERE
	view_user_id = %s 
	AND user_id = %s 
GROUP BY
	type,
	model_id
ORDER BY last_created_at desc", $user_info['id'], $targetUserId);
        $result = M()->query($sql);
        $result = empty($result) ? [] : $result;
        $userService = new UserService();

        foreach ($result as $key => $item) {
            if ($item['type'] == UserViewLogModel::TYPE_CARD) {
                $title = '个人主页';
                $cardInfo = $userService->card($item['user_id']);
                $result[$key]['extend'] = $cardInfo ? [
                    'id' => arr_get($cardInfo, 'id'),
                    'image' => arr_get($cardInfo, 'lit_pic'),
                    'title' => '我的名片',
                ] : [];
            } else {
                $articleInfo = (new ArticleService())->articleInfo($item['model_id'], ['id', 'title', 'lit_pic']);
                $result[$key]['extend'] = [
                    'id' => arr_get($articleInfo, 'id'),
                    'image' => arr_get($articleInfo, 'lit_pic'),
                    'title' => arr_get($articleInfo, 'title'),
                ];
                $title = "文章《" . arr_get($articleInfo, 'title') . "》";
            }
            $allViewSecond = $item['all_view_second'];
            $result[$key]['view_title'] = $title;
            $result[$key]['view_second_des'] = ($allViewSecond > 60) ? floor($allViewSecond/ 60) . '分钟' : max($allViewSecond, 1) . '秒';
            $result[$key]['zuijin_view_time'] = format_date(strtotime($item['last_created_at']));;
        }

        $info = UserData::getUserInfoById($targetUserId);
        $data['user_headimg'] = $info['user_headimg'];
        $data['user_nickname'] = $info['user_nickname'];
        $data['c_weixin'] = $info['c_weixin'];
        $data['user_info'] = $user_info;
        $data['list'] = $result;

        $this->return_app_data(1, $data);
    }

    public function apiGetCardTime()
    {
        $user_info = $this->checkUserUtoken();
        $card_id = $_POST['card_id'] ? intval($_POST['card_id']) : 0;
        $timer = $_POST['timer'] ? intval($_POST['timer']) : 0;
        $card_m = new UserCardListModel();
        $car_info = $card_m->getInfo(['id' => $card_id]);
        $view_user_id = $car_info['user_id'] ? intval($car_info['user_id']) : 0;
        if ($user_info['id'] == $view_user_id) {
            $this->return_app_data(1, '自己无需记录');
        }
        $addLogStatus = (new UserViewLogService())->setParams([
            'user_id' => $user_info['id'],
            'type' => UserViewLogModel::TYPE_CARD,
            'view_user_id' => $view_user_id,
            'model_id' => $card_id,
            'view_second' => $timer,
        ])->addRecord();
        if ($addLogStatus) {
            //		发送浏览模版消息
            $send_user_info = UserData::getUserInfoById($view_user_id);
            if ($send_user_info['is_vip'] == 1 && $send_user_info['view_log_tip_type'] == 1) {
                //	立即发送提醒
                (new WxGongZhongService())->sendViewMessage($send_user_info['id']);
            }
            $this->return_app_data(1, '记录成功');
        }
    }

    public function apiGetArticleTime()
    {
        $user_info = $this->checkUserUtoken();
        $article_id = $_POST['article_id'] ? intval($_POST['article_id']) : 0;
        $timer = $_POST['timer'] ? intval($_POST['timer']) : 0;
        $article_info = (new ArticleService())->articleInfo($article_id);
        $view_user_id = $article_info['user_id'] ? intval($article_info['user_id']) : 0;
        if ($user_info['id'] == $view_user_id) {
            $this->return_app_data(1, '自己无需记录');
        }
        $addLogStatus = (new UserViewLogService())->setParams([
            'user_id' => $user_info['id'],
            'type' => UserViewLogModel::TYPE_ARTICLE,
            'view_user_id' => $view_user_id,
            'model_id' => $article_id,
            'view_second' => $timer,
        ])->addRecord();
        if ($addLogStatus) {
            //		发送浏览模版消息
            $send_user_info = UserData::getUserInfoById($article_info['user_id']);
            if ($send_user_info['is_vip'] == UserModel::IS_VIP && $send_user_info['view_log_tip_type'] == UserModel::TIP_TYPE_NOW) {
                //	立即发送提醒
                (new WxGongZhongService())->sendViewMessage($send_user_info['id']);
            }
            $this->return_app_data(1, '记录成功');
        }
    }

    //	vip设置
    public function vipSetting()
    {
        $user_info = $this->checkUserUtoken();
        $this->return_app_data(1, $user_info);
    }

    //	设置水印
    public function watermarkSetting()
    {
        $user_info = $this->checkUserUtoken();
        if ($user_info['is_vip'] == 0) {
            $this->return_app_data(0, '请先开通VIP');
        }
        $watermark = $_POST['watermark'] ? trim($_POST['watermark']) : '';
        if (empty($watermark)) {
            $this->return_app_data(0, '请输入水印内容');
        }
        $save['watermark_title'] = $watermark;
        $save['update_time'] = time();
        $saveWater = M("user")->where(['id' => $user_info['id']])->save($save);
        if ($saveWater) {
            $this->return_app_data(1, '更新成功');
        } else {
            $this->return_app_data(0, '更新失败');
        }
    }

    //	设置提醒时间
    public function logTip()
    {
        $user_info = $this->checkUserUtoken();
        if ($user_info['is_vip'] == 0) {
            $this->return_app_data(0, '请先开通VIP');
        }
        $view_log_tip_type = $_POST['view_log_tip_type'] ? trim($_POST['view_log_tip_type']) : 0;
        $save['view_log_tip_type'] = $view_log_tip_type;
        //		判断多久提醒一次
        if ($view_log_tip_type == 2) {
            $save['log_tip_time'] = strtotime("+15 minutes", time());
        } elseif ($view_log_tip_type == 3) {
            $save['log_tip_time'] = strtotime('+1 hour', time());
        } elseif ($view_log_tip_type == 4) {
            $save['log_tip_time'] = strtotime('+3 hour', time());
        } else {
            $save['log_tip_time'] = 0;
        }
        $save['update_time'] = time();
        $saveWater = M("user")->where(['id' => $user_info['id']])->save($save);
        if ($saveWater) {
            $this->return_app_data(1, '更新成功');
        } else {
            $this->return_app_data(0, '更新失败');
        }
    }
}

?>
